<?php

namespace app\jy\logic;
use think\Db;
use think\cache\driver\Redis;
class UserLogic{

    public $error = '';//错误提示

    /**
     * 用户领取记录
     */
    public function userReceive($uid){
        $db = Db::name('user_receive')->field('id,title,num,price,amount,add_time,img,status,waybill_number,type')->where(['uid'=>$uid])->select();
        if ( !$db ) {
            $this->error = '无数据';
            return false;
        }
        return $db;
    }

    /**
     * 获取领取地址信息
     */
    public function singleReceive($receive_id){
        $db = Db::name('user_receive')->field('name,mobile,province,address')->where(['id'=>$receive_id])->find();
        if ($db) {
            $db['mobile'] = getMobileHide($db['mobile']);
        }
        return $db;
    }

    /**
     * 用户收货地址列表
     */
    public function collectAddressList($uid){
        $db = Db::name('user_address')->field('id,name,mobile,province,address,is_default')->where(['uid'=>$uid])->select();
        if ( !$db ) {
            $this->error = '无数据';
            return false;
        }
        return $db;
    }

    /**
     * 增加用户收货地址
     */
    public function addAddress($map,$uid){
        //验证手机号
        // $checkPhone = $this->checkPhone($map['mobile']);
        // if ($checkPhone === false) {
        //     $this->error = '手机号格式错误';
        //     return false;
        // }
        if (!$map['name'] || !$map['province'] || !$map['address']) {
            $this->error = '请检查填写信息';
            return false;
        }
        //判断地址是否已存在10个
        $checkNum = Db::name('user_address')->where(['uid'=>$uid])->count();
        if ($checkNum >= 10) {
            $this->error = '收货地址已达到上限';
            return false;
        }
        $map['uid'] = $uid;
        $map['add_time'] = date('Y-m-d H:i:s');
        Db::startTrans();
        try {
            //如果设置默认把其他改成非默认
            if ($map['is_default'] == '1') {
                Db::name('user_address')->where(['uid'=>$uid])->update(['is_default'=>2]);
            }
            Db::name('user_address')->insert($map);
            //提交事务
            Db::commit();
        } catch (\Exception $e) {
            //回滚事务
            Db::rollback();
            $this->error = '添加错误';
            return false;
        }
        return true;
    }

    /**
     * 编辑用户收货地址
     */
    public function editAddress($map,$uid){
        // $checkPhone = $this->checkPhone($map['mobile']);
        // if ($checkPhone === false) {
        //     $this->error = '手机号格式错误';
        //     return false;
        // }
        if (!$map['name'] || !$map['province'] || !$map['address']) {
            $this->error = '请检查填写信息';
            return false;
        }
        Db::startTrans();
        try {
            //如果设置默认把其他改成非默认
            if ($map['is_default'] == '1') {
                Db::name('user_address')->where(['uid'=>$uid])->update(['is_default'=>2]);
            }
            $map['update_time'] = date('Y-m-d H:i:s');
            Db::name('user_address')->where(['id'=>$map['id']])->update($map);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error = '修改错误';
            return false;
        }
        return true;
    }

    //验证手机号
    public function checkPhone($value)
    {
        if (strlen($value) != 11) {
            return false;
        }
        $res = preg_match("/^[1][3,4,5,6,7,8,9][0-9]{9}$/", $value, $matches);
        if (!$res) {
            return false;
        }
        return true;
    }

    /**
     * 删除收货地址
     */
    public function delAddress($id){
        $db = Db::name('user_address')->where(['id'=>$id])->delete();
        if (!$db) {
            $this->error = '删除地址错误';
            return false;
        }
        return true;
    }

    /**
     * 瓶塞列表
     */
    public function corkList($uid){
        $db = Db::name('user_points')->field('nickname,mobile,title,point_num,add_time')->order('add_time desc')->where(['uid'=>$uid,'type'=>1])->select();
        if ( !$db ) {
            $this->error = '无数据';
            return false;
        }
        foreach ($db as $key => $value) {
            $db[$key]['mobile'] = getMobileHide($value['mobile']);
        }
        return $db;
    }

    /**
     * 用户订单列表
     */
    public function userOrderList($type,$uid){
        $where['uid'] = $uid;
        $where['is_delete']  = 2;//用户未删除
        $where['his_delete'] = 2;//管理后台未删除
        switch ($type) {
            case '2':
                $where['status'] = 0;
                break;
            case '3':
                $where['status'] = ['in',[1,2]];
                break;
            case '4':
                $where['status'] = ['in',[3,10]];
                break;
            default:
                # code...
                break;
        }
        $db = Db::name('order')->field('id,add_time,title,num,price,amount,img,status,over_time')->order('add_time desc')->where($where)->select();
        if ( !$db ) {
            $this->error = '无数据';
            return false;
        }
        // foreach ($db as $k => $v) {
        //     if ($v['status'] == '0') {
        //         $type = 2;
        //     }
        //     if ($v['status'] == '1' || $v['status'] == '2') {
        //         $type = 3;
        //     }
        //     if ($v['status'] == '3' || $v['status'] == '10') {
        //         $type = 4;
        //     }
        //     $db[$k]['type'] = $type;
        // }
        return $db;
    }

    /**
     * 用户订单操作
     */
    public function orderOperate($order_id,$operateType){
        $detail = Db::name('order')->where(['id'=>$order_id,'is_delete'=>2,'his_delete'=>2])->find();
        if (!$detail) {
            $this->error = '未查找到订单！';
            return false;
        }
        switch ($operateType) {
            case '1'://取消订单
                //判断是否已做取消处理
                if ($detail['status'] == '10') {
                    return true;
                }
                //判断订单是待付款状态
                if ($detail['status'] != '0') {
                    $this->error = '订单状态已改变！';
                    return false;
                }
                $map['status'] = 10;
                break;
            case '2'://确认收货
                //判断是否是收货状态
                if ($detail['status'] == '3') {
                    return true;
                }
                //判断订单是已发货状态
                if ($detail['status'] != '2') {
                    $this->error = '订单未发货，暂无法确认收货！';
                    return false;
                }
                $map['status'] = 3;
                break;
            case '3'://删除订单
                //判断是否是删除状态
                if ($detail['is_delete'] == '1') {
                    return true;
                }
                //判断订单是已发货状态
                if ($detail['status'] != '10') {
                    $this->error = '订单状态已改变！';
                    return false;
                }
                $map['is_delete'] = 1;
                break;
            
            default:
                $this->error = '参数有误！';
                return false;
                break;
        }
        $db = Db::name('order')->where(['id'=>$order_id])->update($map);
        if ( !$db ) {
            $this->error = '操作失败';
            return false;
        }
        if ($operateType == '1') {
            //增加库存
            $Redis = new redis();
            $Redis->inc('stock:order',$detail['num']);
        }
        return true;
    }

    /**
     * 用户订单详情
     */
    public function orderDetail($order_id){
        $db = Db::name('order')->field('over_time,order_no,add_time,name,mobile,province,address,title,num,price,amount,img,status,waybill_number')->where(['id'=>$order_id,'is_delete'=>2,'his_delete'=>2])->find();
        if (!$db) {
            $this->error = '未查找到订单！';
            return false;
        }
        //获取物流信息
        $db['logistics'] = '';
        $db['countDown'] = '';
        if ($db['status'] == '2' || $db['status'] == '3') {
            $info = getLogisticsInfo($db['waybill_number']);
            $db['logistics'] = $info['result']['list'];
        }
        //待付款时计算倒计时
        if ($db['status'] == '0') {
            $time3 = strtotime($db['over_time']) - strtotime('now');
            $db['countDown'] = $time3 >= 0 ? $time3 : 0;
        }
        $db['mobile'] = getMobileHide($db['mobile']);
        return $db;
    }
    
}